package com.codebroker.util.zookeeper.support;


import com.codebroker.util.zookeeper.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.Executor;

public abstract class AbstractZookeeperClient<TargetDataListener, TargetChildListener> implements ZookeeperClient {

	protected static final Logger logger = LoggerFactory.getLogger(AbstractZookeeperClient.class);

	private final ZookeeperURL zookeeperUrl;

	private final Set<StateListener> stateListeners = new CopyOnWriteArraySet();

	private final ConcurrentMap<String, ConcurrentMap<ChildListener, TargetChildListener>> childListeners = new ConcurrentHashMap();

	private final ConcurrentMap<String, ConcurrentMap<DataListener, TargetDataListener>> listeners = new ConcurrentHashMap();

	private volatile boolean closed = false;

	public AbstractZookeeperClient(ZookeeperURL zookeeperUrl) {
		this.zookeeperUrl = zookeeperUrl;
	}

	@Override
	public ZookeeperURL getZookeeperUrl() {
		return zookeeperUrl;
	}

	@Override
	public void create(String path, boolean ephemeral) {
		if (!ephemeral) {
			if (checkExists(path)) {
				return;
			}
		}
		int i = path.lastIndexOf('/');
		if (i > 0) {
			create(path.substring(0, i), false);
		}
		if (ephemeral) {
			createEphemeral(path);
		} else {
			createPersistent(path);
		}
	}

	@Override
	public void addStateListener(StateListener listener) {
		stateListeners.add(listener);
	}

	@Override
	public void removeStateListener(StateListener listener) {
		stateListeners.remove(listener);
	}

	public Set<StateListener> getSessionListeners() {
		return stateListeners;
	}

	@Override
	public List<String> addChildListener(String path, final ChildListener listener) {
		ConcurrentMap<ChildListener, TargetChildListener> listeners = childListeners.get(path);
		if (listeners == null) {
			childListeners.putIfAbsent(path, new ConcurrentHashMap());
			listeners = childListeners.get(path);
		}
		TargetChildListener targetListener = listeners.get(listener);
		if (targetListener == null) {
			listeners.putIfAbsent(listener, createTargetChildListener(path, listener));
			targetListener = listeners.get(listener);
		}
		return addTargetChildListener(path, targetListener);
	}

	@Override
	public void addDataListener(String path, DataListener listener) {
		this.addDataListener(path, listener, null);
	}

	@Override
	public void addDataListener(String path, DataListener listener, Executor executor) {
		ConcurrentMap<DataListener, TargetDataListener> dataListenerMap = listeners.get(path);
		if (dataListenerMap == null) {
			listeners.putIfAbsent(path, new ConcurrentHashMap());
			dataListenerMap = listeners.get(path);
		}
		TargetDataListener targetListener = dataListenerMap.get(listener);
		if (targetListener == null) {
			dataListenerMap.putIfAbsent(listener, createTargetDataListener(path, listener));
			targetListener = dataListenerMap.get(listener);
		}
		addTargetDataListener(path, targetListener, executor);
	}

	@Override
	public void removeDataListener(String path, DataListener listener ){
		ConcurrentMap<DataListener, TargetDataListener> dataListenerMap = listeners.get(path);
		if (dataListenerMap != null) {
			TargetDataListener targetListener = dataListenerMap.remove(listener);
			if(targetListener != null){
				removeTargetDataListener(path, targetListener);
			}
		}
	}

	@Override
	public void removeChildListener(String path, ChildListener listener) {
		ConcurrentMap<ChildListener, TargetChildListener> listeners = childListeners.get(path);
		if (listeners != null) {
			TargetChildListener targetListener = listeners.remove(listener);
			if (targetListener != null) {
				removeTargetChildListener(path, targetListener);
			}
		}
	}

	protected void stateChanged(int state) {
		for (StateListener sessionListener : getSessionListeners()) {
			sessionListener.stateChanged(state);
		}
	}

	@Override
	public void close() {
		if (closed) {
			return;
		}
		closed = true;
		try {
			doClose();
		} catch (Throwable t) {
			logger.warn(t.getMessage(), t);
		}
	}

	@Override
	public void create(String path, String content, boolean ephemeral) {
		if (checkExists(path)) {
			delete(path);
		}
		int i = path.lastIndexOf('/');
		if (i > 0) {
			create(path.substring(0, i), false);
		}
		if (ephemeral) {
			createEphemeral(path, content);
		} else {
			createPersistent(path, content);
		}
	}

	@Override
	public String getContent(String path) {
		if (!checkExists(path)) {
			return null;
		}
		return doGetContent(path);
	}

	protected abstract void doClose();

	protected abstract void createPersistent(String path);

	protected abstract void createEphemeral(String path);

	protected abstract void createPersistent(String path, String data);

	protected abstract void createEphemeral(String path, String data);

	protected abstract boolean checkExists(String path);

	protected abstract TargetChildListener createTargetChildListener(String path, ChildListener listener);

	protected abstract List<String> addTargetChildListener(String path, TargetChildListener listener);

	protected abstract TargetDataListener createTargetDataListener(String path, DataListener listener);

	protected abstract void addTargetDataListener(String path, TargetDataListener listener);

	protected abstract void addTargetDataListener(String path, TargetDataListener listener, Executor executor);

	protected abstract void removeTargetDataListener(String path, TargetDataListener listener);

	protected abstract void removeTargetChildListener(String path, TargetChildListener listener);

	protected abstract String doGetContent(String path);

}
